package com.uzai.console.service.takebal.impl;

import com.uzai.common.entity.User;
import com.uzai.common.enums.TakeBalStatusEnum;
import com.uzai.common.enums.TransTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.takebal.usertakebal.*;
import com.uzai.console.entity.UserTakeBal;
import com.uzai.console.mapper.AlipayMchAuthMapper;
import com.uzai.console.mapper.UserTakeBalMapper;
import com.uzai.console.service.takebal.UserTakeBalService;
import com.uzai.console.service.takebal.UserTakeBalSyncService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.vo.alipaymchbatch.AlipayMchBatchTransVo;
import com.uzai.console.vo.takebal.usertakebal.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: liuqi
 * @Date: 2019/11/27 11:23
 * @Description:
 */
@Service
public class UserTakeBalSyncServiceImpl implements UserTakeBalSyncService {

    private static Logger logger = LoggerFactory.getLogger(UserTakeBalSyncServiceImpl.class);

    @Autowired
    private UserTakeBalService userTakeBalService;
    @Autowired
    private UserTakeBalMapper userTakeBalMapper;
    @Autowired
    private AlipayMchAuthMapper alipayMchAuthMapper;
    @Autowired
    private UserService userService;


    /**
     * 批量发送提现卡片
     *
     * @param userTakeBalSendCardListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public UserTakeBatchSendcardVo batchSendcard(UserTakeBalSendCardListDto userTakeBalSendCardListDto) {

        UserTakeBatchSendcardVo userTakeBatchSendcardVo = new UserTakeBatchSendcardVo();
        int successNum = 0;
        int failNum = 0;

        List<Long> idList = userTakeBalSendCardListDto.getIdList();

        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        for (Long id : idList) {
            try {

                UserTakeBal userTakeBal = userTakeBalMapper.selectById(id, userTakeBalSendCardListDto.getMerId());

                if (userTakeBal == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
                }

                if (userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_PENDING.getValue().intValue() && userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue().intValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该提现不是待处理状态或者自动提现失败");
                }

                User user = userService.findUserInfo(userTakeBal.getUserId(), userTakeBal.getDeviceType(), userTakeBalSendCardListDto.getMerId());
                if (user == null) {
                    userTakeBal.setStatus(TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue());
                    userTakeBal.setTransType(TransTypeEnum.REDCARD.getValue());
                    userTakeBal.setFailMsg("会员不存在");
                    userTakeBal.setUpdateTime(DateUtil.getNowTime());
                    int i = userTakeBalMapper.updateStatus(userTakeBal);
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员不存在");
                }

                //是否开启会员余额负数不提现验证
                if (Tools.getInteger(userTakeBalSendCardListDto.getUserBalFlag()).intValue() == 1) { //开启，则需要判断会员余额是否为负数
                    if (Tools.getDouble(user.getBalance()).doubleValue() < 0) {
                        userTakeBal.setStatus(TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue());
                        userTakeBal.setTransType(TransTypeEnum.REDCARD.getValue());
                        userTakeBal.setFailMsg("会员余额为负数不处理");
                        userTakeBal.setUpdateTime(DateUtil.getNowTime());
                        int i = userTakeBalMapper.updateStatus(userTakeBal);
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员余额为负数不处理");
                    }
                }

                UserTakeBalSendCardDto userTakeBalSendCardDto = new UserTakeBalSendCardDto();
                userTakeBalSendCardDto.setMerId(userTakeBalSendCardListDto.getMerId());
                userTakeBalSendCardDto.setId(id);
                userTakeBalSendCardDto.setMessage(userTakeBalSendCardListDto.getMessage());
                userTakeBalService.sendcard(userTakeBalSendCardDto);
                successNum++;
            } catch (Exception e) {
                failNum++;
                logger.error("---batchSendcard error, id={},error={}", id, e.getMessage());
            }
        }

        userTakeBatchSendcardVo.setSuccessNum(successNum);
        userTakeBatchSendcardVo.setFailNum(failNum);
        return userTakeBatchSendcardVo;

    }

    /**
     * 批量微信转账
     *
     * @param userTakeBalIdListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public UserTakeBatchWxpayVo batchWxpay(UserTakeBalIdListDto userTakeBalIdListDto) {

        UserTakeBatchWxpayVo userTakeBatchWxpayVo = new UserTakeBatchWxpayVo();
        int successNum = 0;
        int failNum = 0;

        List<Long> idList = userTakeBalIdListDto.getIdList();

        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        for (Long id : idList) {
            try {

                UserTakeBal userTakeBal = userTakeBalMapper.selectById(id, userTakeBalIdListDto.getMerId());

                if (userTakeBal == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
                }

                if (userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_PENDING.getValue().intValue() && userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue().intValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该提现不是待处理状态或者自动提现失败");
                }

                User user = userService.findUserInfo(userTakeBal.getUserId(), userTakeBal.getDeviceType(), userTakeBalIdListDto.getMerId());
                if (user == null) {
                    userTakeBal.setStatus(TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue());
                    userTakeBal.setTransType(TransTypeEnum.WEICHAT.getValue());
                    userTakeBal.setFailMsg("会员不存在");
                    userTakeBal.setUpdateTime(DateUtil.getNowTime());
                    int i = userTakeBalMapper.updateStatus(userTakeBal);
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员不存在");
                }

                //是否开启会员余额负数不提现验证
                if (Tools.getInteger(userTakeBalIdListDto.getUserBalFlag()).intValue() == 1) { //开启，则需要判断会员余额是否为负数
                    if (Tools.getDouble(user.getBalance()).doubleValue() < 0) {
                        userTakeBal.setStatus(TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue());
                        userTakeBal.setTransType(TransTypeEnum.WEICHAT.getValue());
                        userTakeBal.setFailMsg("会员余额为负数不处理");
                        userTakeBal.setUpdateTime(DateUtil.getNowTime());
                        int i = userTakeBalMapper.updateStatus(userTakeBal);
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员余额为负数不处理");
                    }
                }

                UserTakeBalIdDto userTakeBalIdDto = new UserTakeBalIdDto();
                userTakeBalIdDto.setMerId(userTakeBalIdListDto.getMerId());
                userTakeBalIdDto.setId(id);
                userTakeBalService.wxpay(userTakeBalIdDto);
                successNum++;
            } catch (Exception e) {
                failNum++;
                logger.error("---batchWxpay error, id={},error={}", id, e.getMessage());
            }
        }

        userTakeBatchWxpayVo.setSuccessNum(successNum);
        userTakeBatchWxpayVo.setFailNum(failNum);
        return userTakeBatchWxpayVo;
    }

    /**
     * 批量支付宝转账
     *
     * @param userTakeBalIdListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public UserTakeBatchAlipayVo batchAlipay(UserTakeBalIdListDto userTakeBalIdListDto) {

        UserTakeBatchAlipayVo userTakeBatchAlipayVo = new UserTakeBatchAlipayVo();
        int successNum = 0;
        int failNum = 0;

        List<Long> idList = userTakeBalIdListDto.getIdList();

        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        for (Long id : idList) {
            try {

                UserTakeBal userTakeBal = userTakeBalMapper.selectById(id, userTakeBalIdListDto.getMerId());

                if (userTakeBal == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
                }

                if (userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_PENDING.getValue().intValue() && userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue().intValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该提现不是待处理状态或者自动提现失败");
                }

                User user = userService.findUserInfo(userTakeBal.getUserId(), userTakeBal.getDeviceType(), userTakeBalIdListDto.getMerId());
                if (user == null) {
                    userTakeBal.setStatus(TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue());
                    userTakeBal.setTransType(TransTypeEnum.ALIPAY.getValue());
                    userTakeBal.setFailMsg("会员不存在");
                    userTakeBal.setUpdateTime(DateUtil.getNowTime());
                    int i = userTakeBalMapper.updateStatus(userTakeBal);
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员不存在");
                }

                //是否开启会员余额负数不提现验证
                if (Tools.getInteger(userTakeBalIdListDto.getUserBalFlag()).intValue() == 1) { //开启，则需要判断会员余额是否为负数
                    if (Tools.getDouble(user.getBalance()).doubleValue() < 0) {
                        userTakeBal.setStatus(TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue());
                        userTakeBal.setTransType(TransTypeEnum.ALIPAY.getValue());
                        userTakeBal.setFailMsg("会员余额为负数不处理");
                        userTakeBal.setUpdateTime(DateUtil.getNowTime());
                        int i = userTakeBalMapper.updateStatus(userTakeBal);
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员余额为负数不处理");
                    }
                }


                UserTakeBalIdDto userTakeBalIdDto = new UserTakeBalIdDto();
                userTakeBalIdDto.setMerId(userTakeBalIdListDto.getMerId());
                userTakeBalIdDto.setId(id);
                userTakeBalService.alipay(userTakeBalIdDto);
                successNum++;
            } catch (Exception e) {
                failNum++;
                logger.error("---batchAlipay error, id={},error={}", id, e.getMessage());
            }
        }

        userTakeBatchAlipayVo.setSuccessNum(successNum);
        userTakeBatchAlipayVo.setFailNum(failNum);

        return userTakeBatchAlipayVo;
    }

    /**
     * 批量拒绝并偿还
     *
     * @param userTakeBalIdListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public UserTakeBatchRefuseAndReturnVo batchRefuseAndReturnUserTakeBal(UserTakeBalIdListDto userTakeBalIdListDto) {
        UserTakeBatchRefuseAndReturnVo userTakeBatchRefuseAndReturnVo = new UserTakeBatchRefuseAndReturnVo();
        int successNum = 0;
        int failNum = 0;

        List<Long> idList = userTakeBalIdListDto.getIdList();

        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        for (Long id : idList) {
            try {
                UserTakeBalIdDto userTakeBalIdDto = new UserTakeBalIdDto();
                userTakeBalIdDto.setMerId(userTakeBalIdListDto.getMerId());
                userTakeBalIdDto.setId(id);
                userTakeBalService.refuseAndReturnUserTakeBal(userTakeBalIdDto);
                successNum++;
            } catch (Exception e) {
                failNum++;
                logger.error("---batchRefuseAndReturnUserTakeBal error, id={},error={}", id, e.getMessage());
            }
        }

        userTakeBatchRefuseAndReturnVo.setSuccessNum(successNum);
        userTakeBatchRefuseAndReturnVo.setFailNum(failNum);

        return userTakeBatchRefuseAndReturnVo;
    }

    /**
     * 批量拒绝并扣除
     *
     * @param userTakeBalIdListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public UserTakeBatchRefuseAndDecUserVo batchRefuseAndDecUserTakeBal(UserTakeBalIdListDto userTakeBalIdListDto) {
        UserTakeBatchRefuseAndDecUserVo userTakeBatchRefuseAndDecUserVo = new UserTakeBatchRefuseAndDecUserVo();
        int successNum = 0;
        int failNum = 0;

        List<Long> idList = userTakeBalIdListDto.getIdList();

        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        for (Long id : idList) {
            try {
                UserTakeBalIdDto userTakeBalIdDto = new UserTakeBalIdDto();
                userTakeBalIdDto.setMerId(userTakeBalIdListDto.getMerId());
                userTakeBalIdDto.setId(id);
                userTakeBalService.refuseAndDecUserTakeBal(userTakeBalIdDto);
                successNum++;
            } catch (Exception e) {
                failNum++;
                logger.error("---batchRefuseAndDecUserTakeBal error, id={},error={}", id, e.getMessage());
            }
        }

        userTakeBatchRefuseAndDecUserVo.setSuccessNum(successNum);
        userTakeBatchRefuseAndDecUserVo.setFailNum(failNum);

        return userTakeBatchRefuseAndDecUserVo;
    }


    /**
     * 批量支付宝转账(个人)
     *
     * @param userTakeBalAlipayMchBatchDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public AlipayMchBatchTransVo batchAlipayMch(UserTakeBalAlipayMchBatchDto userTakeBalAlipayMchBatchDto) {
        //提现id列表
        List<Long> idList = userTakeBalAlipayMchBatchDto.getIdList();
        //支付宝授权id
        Long alipayMchAuthId = userTakeBalAlipayMchBatchDto.getAlipayMchAuthId();
        //运营商id
        Long merId = userTakeBalAlipayMchBatchDto.getMerId();
        if (alipayMchAuthId == null || merId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        if (idList == null && idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //临时保存可以正确提交的提现id列表
        List<Long> idList_correct = new ArrayList<>();

        for (Long id : idList) {
            UserTakeBal userTakeBal = userTakeBalMapper.selectById(id, merId);

            if (userTakeBal == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
            }

            if (userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_PENDING.getValue().intValue() && userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue().intValue()) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该提现不是待处理状态或者自动提现失败");
            }

            Double takeBal = Tools.getDouble(userTakeBal.getTakeBal());

            if (takeBal.doubleValue() < 1.0) {
                userTakeBal.setStatus(TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue());
                userTakeBal.setTransType(TransTypeEnum.ALIPAYPARTNER.getValue());
                userTakeBal.setFailMsg("提现金额必须大于等于1才能走支付宝个人转账");
                userTakeBal.setUpdateTime(DateUtil.getNowTime());
                int i = userTakeBalMapper.updateStatus(userTakeBal);
                continue;
                //throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现金额必须大于等于1才能走支付宝个人转账");
            }

            //查询用户
            User user = userService.findUserInfo(userTakeBal.getUserId(), userTakeBal.getDeviceType(), merId);
            if (user == null) {
                userTakeBal.setStatus(TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue());
                userTakeBal.setTransType(TransTypeEnum.ALIPAYPARTNER.getValue());
                userTakeBal.setFailMsg("该用户不存在");
                userTakeBal.setUpdateTime(DateUtil.getNowTime());
                int i = userTakeBalMapper.updateStatus(userTakeBal);
                continue;
                //throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
            }

            //是否开启会员余额负数不提现验证
            if (Tools.getInteger(userTakeBalAlipayMchBatchDto.getUserBalFlag()).intValue() == 1) { //开启，则需要判断会员余额是否为负数
                if (Tools.getDouble(user.getBalance()).doubleValue() < 0) {
                    userTakeBal.setStatus(TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue());
                    userTakeBal.setTransType(TransTypeEnum.ALIPAYPARTNER.getValue());
                    userTakeBal.setFailMsg("会员余额为负数不处理");
                    userTakeBal.setUpdateTime(DateUtil.getNowTime());
                    int i = userTakeBalMapper.updateStatus(userTakeBal);
                    continue;
                    //throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员余额为负数不处理");
                }
            }

            //该会员未填写支付宝账户
            if (StringUtils.isBlank(user.getAlipayAccount()) || StringUtils.isBlank(user.getAlipayName())) {
                userTakeBal.setStatus(TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue());
                userTakeBal.setTransType(TransTypeEnum.ALIPAYPARTNER.getValue());
                userTakeBal.setFailMsg("该会员没有支付宝账户信息");
                userTakeBal.setUpdateTime(DateUtil.getNowTime());
                int i = userTakeBalMapper.updateStatus(userTakeBal);
                continue;
                //throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员没有支付宝账户信息");
            }
            //经过检验，可以办理支付宝个人转账的id添加到临时id列表
            idList_correct.add(id);
        }

        if (idList_correct.size() == 0) {//
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择的记录中都不符合支付宝个人转账条件");
        }

        userTakeBalAlipayMchBatchDto.setIdList(idList_correct);

        return userTakeBalService.batchAlipayMch(userTakeBalAlipayMchBatchDto);
    }


}
